package com.wangjiacai.utils.translate.google;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wangjiacai.utils.translate.Translate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.io.InputStreamReader;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;

public class GoogleTranslate implements Translate {

    private static ScriptEngine engine;
    static {
        ScriptEngineManager manager = new ScriptEngineManager();
        engine = manager.getEngineByName("javascript");
        try(InputStreamReader scriptReader=new InputStreamReader(GoogleTranslate.class.getResourceAsStream("/gettk.js"), "utf-8")){
            engine.eval(scriptReader);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private RestTemplate restTemplate = new RestTemplate();
    private static final String url = "https://translate.google.cn/translate_a/single?q={1}&sl={2}&tl={3}&client=webapp&dt=t&tk={4}";
    private static final String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36";
    private static String tkk;


    public GoogleTranslate(){
        tkk = this.getTKK();
    }

    private HttpEntity getHttpEntity(){
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("User-Agent", USER_AGENT);
        HttpEntity httpEntity = new HttpEntity(httpHeaders);
        return httpEntity;
    }

    private String getTKK() {
        try {
            String result = restTemplate.exchange("https://translate.google.cn/", HttpMethod.GET, getHttpEntity(), String.class).getBody();
            int index=result.indexOf("tkk");
            return result.substring(result.indexOf(":",index)+2,result.indexOf(",",index)-1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String getTK(String word, String tkk) {
        try {
            if (engine instanceof Invocable) {
                Invocable invocable = (Invocable)engine;
                return (String)invocable.invokeFunction("tk", word, tkk);
            }
        } catch (Exception var4) {
            var4.printStackTrace();
        }
        return null;
    }

    @Override
    public String translate(String sourceLan, String targetLan, String content) {
        tkk=getTKK();
        String tk=getTK(content,tkk);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, getHttpEntity(), String.class, content, sourceLan, targetLan,tk);
        JSONArray jsonArray = JSONObject.parseArray(response.getBody()).getJSONArray(0).getJSONArray(0);
        return jsonArray.getString(0);
    }

    @Override
    public CompletableFuture<String> translateAsync(String sourceLan, String targetLan, String content) {
        return CompletableFuture.supplyAsync(() -> this.translate(sourceLan, targetLan, content));
    }

    @Override
    public CompletableFuture<String> translateAsync(String sourceLan, String targetLan, String content, Executor executor) {
        return CompletableFuture.supplyAsync(() -> this.translate(sourceLan, targetLan, content), executor);
    }

}
